#include "wcount.h"

char file[255];
FILE* in_file;
int charcount = 0;
int wordcount = 0;
int linecount = 0;


int main(int argc,char* argv[]){
    char* filename;
    if(argc == 1){
        filename = getFileName();
        filename[strlen(filename)-1] = '\0';
    }else if(argc == 2){
        
        filename = &argv[1][0];
        
    }else{
       printf("usage: w2count <optional filename>\n");
       return EXIT_FAILURE;
    }

    if(openFile(filename) == 0){
        printf("Error: unable to open the file\n");
        return EXIT_FAILURE;
    }
    
    countWords();
    
    showResults();
     
    closeFile();
    
    return EXIT_SUCCESS;
}

char* getFileName(){
    printf("File name to count: ");
    fgets(file, sizeof(file), stdin);
    return file;
}

int openFile(char* filename){
    
    in_file = fopen(filename, "r");
    if(in_file == NULL){
        return 0;
    }
    return 1;
}

void countWords(){
    int val;
    int inaword = 0;
    
    while((val = fgetc(in_file)) != EOF){
        charcount++;
        if(val == ' ' | val == '\n'){
            if(inaword == 1){
                wordcount++;
                inaword = 0;
            }
            if(val == '\n'){
                linecount++;
            }
        }
        else if(val > 0 & val < 128){
            if(inaword == 0)
                inaword = 1;
        }
        else
            charcount;   
    }

}

void showResults(){
    printf("Number of characters: %d\n",charcount);
    printf("Number of words: %d\n",wordcount);
    printf("Number of lines: %d\n",linecount);
}

void closeFile(){
    fclose(in_file);
}
